import regular from "@/utils/regular";
import { emitCb, getOption } from "..";
import { loginRequest } from "../utils/request";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isShow: false,
    openImg: "../../img/eye.png",
    closeImg: "../../img/eye-slash.png",
    countDown: null,
    username: "",
    code: "",
    disabled: true,
    option: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const option = getOption()
    this.setData({ option })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },

  async submit(e) {
    const { username, code } = this.data
    const loginRes = await loginRequest("app/user/loginByMobile", {
      mobile: `+86${username}`,
      code,
      lang: "zh"
    })
    console.log("loginRes", loginRes)
    const { code: status, message, data } = loginRes.data
    if (status != 200) {
      wx.showToast({
        title: message,
        icon: "error"
      })
    } else {
      wx.showToast({
        title: "登录成功",
        icon: "success"
      })
      emitCb(data)
      setTimeout(() => {
        wx.navigateBack({ delta: 2 })
      }, 1000);
    }
  },

  toggle: function (e) {
    console.log("hello", this);
    this.setData({ isShow: !this.data.isShow });
  },

  async getCode() {
    const { countDown, username } = this.data;
    if (this.data.countDown) return;
    if (regular.phoneAndEmail.test(username) === false) {
      wx.showToast({
        title: "手机/邮箱非法",
        icon: "error",
      });
      return;
    }
    this.startCountDown();

    const res = await loginRequest("app/user/mobileCode", { mobile: `+86${username}`, lang: "zh" });

    console.log("发送验证码", res);
  },

  startCountDown() {
    let countDown = 60;
    this.setData({
      countDown: countDown,
    });
    const timer = setInterval(() => {
      countDown--;
      this.setData({
        countDown: countDown,
      });
      if (countDown <= 0) {
        clearInterval(timer);
        this.setData({
          countDown: null,
        });
      }
    }, 1000);
  },
});
